package com.framework.modules.job.task;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.framework.entity.sys.*;
import com.framework.entity.ter.TerDistribu;
import com.framework.entity.ter.TerMerchantReport;
import com.framework.service.*;
import com.framework.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.bind.SchemaOutputResolver;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 临时任务，写出来处理一些特殊需求
 *
 * @author wq
 * @date 2019/10/23 13:47
 * @description
 */
@Component("specialTask")
public class SpecialTask {


    @Autowired
    private AgentService agentService;

    @Autowired
    private AgentInfoService agentInfoService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private DistribuService distribuService;

    @Autowired
    private TreeAgentService treeAgentService;

    @Autowired
    private BankService bankService;

    @Autowired
    private TransactionInfoService transactionInfoService;

    @Autowired
    private TerminalInfoService terminalInfoService;

    @Autowired
    private LvRateService lvRateService;


    @Autowired
    private BenefitDayService benefitDayService;

    /**
     * 清理合伙人，合伙人所得全部给上级
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteAgent() {
        List<String> list = Arrays.asList("100810", "889802");


        for (String s : list) {
            //查找到本人
            SysAgent agent = agentService.queryAgentById(Long.valueOf(s));

            //处理上级为该合伙人的合伙人，修改为该合伙人的上级
            List<SysAgent> subAgent = agentService.queryAgentByPid(agent.getAgentId());
            for (SysAgent sysAgent : subAgent) {

                sysAgent.setPid(agent.getPid());
                agentService.updateById(sysAgent);
            }

            //处理该合伙人的余额
            SysAgentInfo infoById = agentInfoService.getAgentInfoById(agent.getAgentId());

            SysAgentInfo upAgentInfo = agentInfoService.getAgentInfoById(agent.getPid());

            upAgentInfo.setTotalAmount(upAgentInfo.getTotalAmount().add(infoById.getTotalAmount()));
            upAgentInfo.setAvailableAmount(upAgentInfo.getAvailableAmount().add(infoById.getAvailableAmount()));
            agentInfoService.updateById(upAgentInfo);

            //删除该合伙人的树形相关

            treeAgentService.delete(new EntityWrapper<SysTreeAgent>().eq("sub_id", agent.getAgentId()));

            //查出所有的商户,报备修改为上级
            List<TerMerchantReport> merchantList = merchantService.queryMerchantByAgentId(agent.getAgentId());

            for (TerMerchantReport report : merchantList) {
                report.setAgentId(agent.getPid());
                merchantService.updateById(report);
            }

            //回退机器给上级
            List<TerDistribu> distribus = distribuService.selectList(new EntityWrapper<TerDistribu>().eq("agent_id", agent.getAgentId())
                    .eq("state", 2)
            );

            for (TerDistribu terDistribu : distribus) {
                TerDistribu distribu = distribuService.selectOne(new EntityWrapper<TerDistribu>().eq("state", 1).eq("to_aid", terDistribu.getAgentId()));
                //System.out.println(terDistribu.getSn());
                distribu.setToAid(null);
                distribu.setState(2);
                distribuService.updateAllColumnById(distribu);
                distribuService.deleteById(terDistribu.getDistribuId());

            }
            //清除银行
            SysBank bank = bankService.queryBankByAgentId(agent.getAgentId());

            if (bank != null) {
                bankService.deleteById(bank.getBankId());
            }
            //清除信息
            agentInfoService.deleteById(infoById.getAgentInfoId());

            //删除注册信息

            agentService.deleteById(agent.getAgentId());


        }


    }


    public void countTran() {
        final BigDecimal MULTINUM = new BigDecimal("10000");
        List<String> monthList=Arrays.asList("2019-04","2019-05","2019-06","2019-07","2019-08","2019-09","2019-10");
       // List<String> monthList = Arrays.asList("2019-04");
        Long agentId = 100902L;
        //自营交易总分润
        BigDecimal ownerBenefit;
        //团队交易总分润
        BigDecimal teamBenefit;

        BigDecimal totalSub=new BigDecimal("0.00");

        for (String s : monthList) {

            System.out.println("开始核算王长林" + s + "月的分润");
            Map<String, Object> result = benefitDayService.queryAgentIdSum(agentId, s);
            ownerBenefit = new BigDecimal("0.00");

            teamBenefit = new BigDecimal("0.00");

            //核算自营
            List<Map<String, Object>> list = transactionInfoService.queryTranByAgentAndMonth(agentId, s);

            //核算上个月的总交易
            Date date = DateUtils.addDateMonths(DateUtils.stringToDate(s, DateUtils.DATE_MONTH_PATTERN), -1);

            BigDecimal bigDecimal = transactionInfoService.querySumTran(agentId, DateUtils.format(date, DateUtils.DATE_MONTH_PATTERN));

            Integer lastGrade = lvRateService.getGradeByTran(bigDecimal, agentId, 1L);
            System.out.println(s+"上月的等级"+lastGrade);
            for (Map<String, Object> map : list) {

                Integer terminalType = (Integer) map.get("terminalType");
                BigDecimal amount = new BigDecimal(map.get("amount").toString());
                String isVip = map.get("isVip").toString();
                Integer rateType= Integer.valueOf(map.get("rateType").toString());
                if(rateType==1){
                    //费率
                    SysLvRate lastRate = lvRateService.queryLvByGrade(1L, lastGrade, terminalType, isVip);

                    BigDecimal benefit = amount.multiply(lastRate.getRate()).divide(MULTINUM, 2, BigDecimal.ROUND_HALF_UP);
                    System.out.println(terminalType+"---------"+amount+"-----"+benefit);
                    ownerBenefit = ownerBenefit.add(benefit);
                }else {
                    BigDecimal ownerRate=new BigDecimal("3");

                    BigDecimal benefit = amount.multiply(ownerRate).divide(MULTINUM, 2, BigDecimal.ROUND_HALF_UP);
                    ownerBenefit = ownerBenefit.add(benefit);
                }




            }
            BigDecimal selfBenefit = new BigDecimal(result.get("selfBenefit").toString());


            System.out.println(s + "原自营:" + selfBenefit);

            System.out.println(s + "自营:" + ownerBenefit);

            BigDecimal temp=selfBenefit.subtract(ownerBenefit);

            totalSub=totalSub.add(temp);


            //团队交易核算
            List<SysAgent> agents = agentService.queryAgentByPid(agentId);
            for (SysAgent agent : agents) {
                //查出下级的所有交易分类
                List<Map<String, Object>> maps = transactionInfoService.querySumTranByAgentAndMonth(agent.getAgentId(),s);

                //查询下级的总交易
                BigDecimal subAmount = transactionInfoService.querySumTran(agent.getAgentId(), DateUtils.format(date, DateUtils.DATE_MONTH_PATTERN));
                //查出下级当时的等级
                Integer subLastGrade = lvRateService.getGradeByTran(subAmount, agent.getAgentId(), 1L);

                for (Map<String, Object> map : maps) {

                    Integer terminalType = (Integer) map.get("terminalType");
                    BigDecimal amount = new BigDecimal(map.get("amount").toString());
                    String isVip = map.get("isVip").toString();
                    Integer rateType= Integer.valueOf(map.get("rateType").toString());
                    if(rateType==1){
                        //王长林的等级
                        SysLvRate lastRate = lvRateService.queryLvByGrade(1L, lastGrade, terminalType, isVip);

                        //下级的等级
                        SysLvRate subLastRate = lvRateService.queryLvByGrade(1L, subLastGrade, terminalType, isVip);

                        BigDecimal rate =lastRate.getRate().subtract(subLastRate.getRate());

                        BigDecimal teamAmount = amount.multiply(rate).divide(MULTINUM);
                        teamAmount=teamAmount.compareTo(new BigDecimal("0.00"))==1?teamAmount:new BigDecimal("0.00");
                        teamBenefit = teamBenefit.add(teamAmount);
                    }else {
                        BigDecimal teamAmount = amount.multiply(new BigDecimal("0.5")).divide(MULTINUM);
                        teamAmount=teamAmount.compareTo(new BigDecimal("0.00"))==1?teamAmount:new BigDecimal("0.00");
                        teamBenefit = teamBenefit.add(teamAmount);
                    }


                }

            }

            BigDecimal teamBenefit1 = new BigDecimal(result.get("teamBenefit").toString());
            System.out.println();
            System.out.println(s+"原团队分润:"+teamBenefit1);
            System.out.println(s+"团队分润:"+teamBenefit);

            BigDecimal temp2=teamBenefit1.subtract(teamBenefit);

            totalSub=totalSub.add(temp2);



            System.out.println("王长林" + s + "月的分润核算结束");
            System.out.println();
        }

        System.out.println(totalSub);
    }

}
